﻿using BrightIdeasSoftware;
using StableDiffusionTools.Forms;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TaggingToolkit.Framework;
using TaggingToolkit.Controls;
using TaggingToolkit.Forms;
using ComponentFactory.Krypton.Toolkit;
using StableDiffusionTools.Progress;

namespace TaggingToolkit.Forms
{
    public partial class TagEditorForm : KryptonForm
    {
        private TypedObjectListView<TagCount> tolvTags;
        private int tagCount = 0;
        public IList<TagCount> ResultTags => tolvTags.Objects;
        private ModelFilter filter;
        private string filterString = "";
        private Throttler<string> filterThrottler;

        public TagEditorForm()
        {
            InitializeComponent();

            Icon = Properties.Resources.wrench_icon;
            addToolStripMenuItem.Image = StableDiffusionTools.Properties.Resources.bullet_add16;
            editToolStripMenuItem.Image = StableDiffusionTools.Properties.Resources.bullet_wrench16;
            removeToolStripMenuItem.Image = StableDiffusionTools.Properties.Resources.bullet_delete16;
            resetToolStripMenuItem.Image = StableDiffusionTools.Properties.Resources.reset16;

            tolvTags = new TypedObjectListView<TagCount>(olvTags);

            tolvTags.GetColumn("Tag").AspectGetter += (o) => o?.DisplayName;
            olvColumnTag.Renderer = new ColoredTextRendererDataTags() { UseGdiTextRendering = false };
            //filter = (olvColumnTag.Renderer as HighlightTextRenderer).Filter = new TextMatchFilter(olvTags);

            tolvTags.GetColumn("Count").AspectGetter += (o) => o?.Count;
            olvColumnCount.Renderer = new HighlightTextRenderer() { UseGdiTextRendering = false };

            tolvTags.GetColumn("Action").AspectGetter += (o) => o?.Action;
            olvColumnAction.Renderer = new HighlightTextRenderer() { UseGdiTextRendering = false };

            olvTags.PrimarySortColumn = olvColumnCount;
            olvTags.PrimarySortOrder = SortOrder.Descending;

            olvTags.IsSearchOnSortColumn = false;

            filter = new ModelFilter(delegate (object x)
            {
                return ((TagCount)x).DisplayName.IndexOf(filterString, StringComparison.OrdinalIgnoreCase) != -1;
            });

            buttonSpecClearText.Click += (s, e) =>
            {
                kryptonTextBoxFilter.Clear();
            };

            KeyDown += (s, e) =>
            {
                if(e.KeyCode == Keys.Escape)
                {
                    DialogResult = DialogResult.Cancel;
                }
            };

            filterThrottler = new Throttler<string>(1000);
            filterThrottler.Update += filterUpdate;

            StartPosition = FormStartPosition.CenterParent;
        }
        [Obsolete("This is not supported in this class.", true)]

        public new void Show(IWin32Window window) { }
        [Obsolete("This is not supported in this class.", true)]
        public new void Show() { }

        public DialogResult ShowDialog(IWin32Window owner, ConcurrentDictionary<string, int> tags, int totalDataTags)
        {
            tagCount = totalDataTags;
            olvTags.AddObjects(tags.Select((a)=> new TagCount(a.Key, a.Value)).ToList());
            return base.ShowDialog(owner);
        }

        private void olvTags_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Delete:
                    if(ResetOrRemoveSelection(TagEditAction.Remove))
                        e.SuppressKeyPress = true;
                    break;
                case Keys.Insert:
                    AddNewItem();
                    e.SuppressKeyPress = true;
                    break;
                case Keys.Back:
                    ResetOrRemoveSelection(TagEditAction.Keep);
                    break;
            }
        }

        private void olvTags_ItemActivate(object sender, EventArgs e)
        {
            EditExistingItem();
        }

        private void kryptonTextBoxFilter_TextChanged(object sender, EventArgs e)
        {
            filterThrottler.PushState(kryptonTextBoxFilter.Text);
        }

        private void filterUpdate(object sender, ThrottlerEventArgs<string> e)
        {
            if (string.IsNullOrEmpty(e.State))
            {
                filterString = "";
                olvTags.ModelFilter = null;
            }
            else
            {
                filterString = e.State;
                olvTags.ModelFilter = filter;
            }
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            var selected = tolvTags.SelectedObjects;
            bool hasMultipleItemsSelected = selected.Count >= 1;
            bool hasSingleItemSelected = selected.Count == 1;
            bool canReset = selected.Where(t => t.Changed).Count() > 0;

            editToolStripMenuItem.Enabled = hasSingleItemSelected;
            removeToolStripMenuItem.Enabled = hasSingleItemSelected || hasMultipleItemsSelected;
            resetToolStripMenuItem.Enabled = canReset;
        }

        private void addToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddNewItem();
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditExistingItem();
        }

        private void AddNewItem()
        {
            using (var input = new InputTagDialog("Add tag", "", "", TagEditAction.AddFront))
            {
                if (input.ShowDialog() == DialogResult.OK)
                {
                    var addTag = new TagCount(input.Result, tagCount) { Action = input.ResultAction };
                    olvTags.AddObject(addTag);
                }
            }
        }

        private void EditExistingItem()
        {
            var o = tolvTags.SelectedObject;
            if (o == null)
                return;

            if (o.Action == TagEditAction.AddBack || o.Action == TagEditAction.AddFront)
            {
                using (var input = new InputTagDialog("Edit tag", "", o.NewName, o.Action))
                {
                    if (input.ShowDialog() == DialogResult.OK)
                    {
                        o.NewName = input.Result;
                        o.Action = input.ResultAction;
                        olvTags.RefreshObject(o);
                    }
                }
            }
            else
            {
                using (var input = new InputDialog("Edit tag", "", o.NewName, false))
                {
                    if (input.ShowDialog() == DialogResult.OK)
                    {
                        o.NewName = input.Result;
                        olvTags.RefreshObject(o);
                        if (olvTags.Groups.Count > 0)
                            olvTags.BuildGroups();
                    }
                }
            }
        }

        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ResetOrRemoveSelection(TagEditAction.Remove);
        }

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ResetOrRemoveSelection(TagEditAction.Keep);
        }

        private bool ResetOrRemoveSelection(TagEditAction editAction)
        {
            var selectedItems = tolvTags.SelectedObjects;
            var updated = new List<TagCount>();
            var removed = new List<TagCount>();
            if (selectedItems.Count > 0)
            {
                for (int i = 0; i < selectedItems.Count; i++)
                {
                    if (selectedItems[i].Action == TagEditAction.AddBack || selectedItems[i].Action == TagEditAction.AddFront)
                    {
                        removed.Add(selectedItems[i]);
                    }
                    else
                    {
                        selectedItems[i].Action = editAction;
                        updated.Add(selectedItems[i]);
                    }
                }
                olvTags.BeginUpdate();
                //if (updated.Count > 0)
                //    olvTags.RefreshObjects(updated);
                if(removed.Count > 0)
                    olvTags.RemoveObjects(removed);
                olvTags.RefreshSelectedObjects();
                if (olvTags.Groups.Count > 0)
                    olvTags.BuildGroups();
                olvTags.EndUpdate();
            }

            return (updated.Count + removed.Count) > 0;
        }
    }
}
